package com.mar.quarkus;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import org.eclipse.microprofile.jwt.JsonWebToken;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLConnection;
import java.security.Principal;
import java.util.List;

/**
 * Description: 例子 .<br>
 *
 * @author jm
 * @since 2020/4/27
 */
@Tag(name = "例子")
@Path("/example")
public class ExampleResource {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExampleResource.class);
    @Inject JsonWebToken jwt;
    private Proxy proxy;
    private String dirPath;

    @PostConstruct
    public void init() {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 7891);
        proxy = new Proxy(Proxy.Type.SOCKS, addr);
        File dir = FileUtil.mkdir(FileUtil.getUserHomePath().concat("/Documents/社科院/2020-06-16/"));
        dirPath = dir.getPath();
        LOGGER.info(dir.getPath());
    }

    @GET
    @Path("/hello")
    @Produces(MediaType.TEXT_PLAIN)
    @Operation(summary = "返回hello")
    public String hello() {
        return "hello";
    }

    @GET
    @Path("/role")
    @RolesAllowed("admin")
    @Produces(MediaType.TEXT_PLAIN)
    @Operation(summary = "需要权限")
    public String admin(@Context SecurityContext ctx) {
        return getUser(ctx);
    }

    private String getUser(SecurityContext ctx) {
        Principal caller = ctx.getUserPrincipal();
        String name = caller == null ? "anonymous" : caller.getName();
        boolean hasJwt = jwt.getClaimNames() != null;
        String helloReply = String.format("谁：%s, 是否HTTPS: %s, Scheme: %s, 是否JWT: %s", name, ctx.isSecure(),
            ctx.getAuthenticationScheme(), hasJwt);
        return helloReply;
    }

    @GET
    @Path("/password/{password}")
    @Produces(MediaType.TEXT_PLAIN)
    @Operation(summary = "返回加密后密钥")
    public String password(@PathParam("password") String password) {
        return SecureUtil.sha256(password);
    }

    @GET
    @Path("/txt")
    @Produces(MediaType.TEXT_PLAIN)
    @Operation(summary = "读取文件")
    public String txt() {
        ClassPathResource resource = new ClassPathResource("url.txt");
        FileReader fileReader = FileReader.create(new File(resource.getAbsolutePath()));
        List<String> lines = fileReader.readLines();
        List<String> fileNames = FileUtil.listFileNames(dirPath);
        lines.forEach(line -> {
            if (StrUtil.isEmpty(line)) {
                return;
            }
            String fileName = line.substring(line.lastIndexOf("/"));
            if (fileNames.contains(fileName.replace("/", ""))) {
                LOGGER.info("skip: {}", fileName);
                return;
            }
            LOGGER.info("line: {}", line);
            // 如果我们知道代理server的名字, 可以直接使用
            InputStream inputStream = getInputStream(line);
            File file = FileUtil.touch(dirPath.concat(fileName));
            try (FileOutputStream fops = new FileOutputStream(file)) {
                IoUtil.copy(inputStream, fops);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return "success";
    }

    private InputStream getInputStream(String line) {
        try {
            URLConnection conn = URLUtil.url(line).openConnection(proxy);
            conn.setConnectTimeout(5 * 1000);
            //设置用户代理(防止屏蔽程序抓取而返回403错误)
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36" +
                " (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36");
            return conn.getInputStream();
        } catch (Exception e) {
            LOGGER.error("获取URL资源失败", e);
            throw new RuntimeException();
        }
    }
}
